package com.ttxz.sample.view


import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.toast.ToastUtils
import com.ttxz.common.base.view.BaseActivity
import com.ttxz.common.utils.log.LogUtil
import com.ttxz.sample.R
import com.ttxz.sample.adapter.ArticleListAdapter
import com.ttxz.sample.adapter.MyBannerAdapter
import com.ttxz.sample.bean.ArticleListBean
import com.ttxz.sample.bean.ArticleListItemBean
import com.ttxz.sample.bean.BannerBean
import com.ttxz.sample.databinding.ActivityMainBinding
import com.ttxz.sample.view.widget.VolumeSettingDialog
import com.ttxz.sample.vm.MainVM
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnBannerListener

//https://github.com/ldlywt/FastJetpack/blob/master/app/src/main/java/com/aisier/ui/ApiActivity.kt
//https://zhuanlan.zhihu.com/p/453978825
class MainActivity : BaseActivity<ActivityMainBinding, MainVM>() {
    private val bannerDatas = mutableListOf<BannerBean>()
    private val articleListDatas = mutableListOf<ArticleListItemBean>()
    private lateinit var articleListAdapter: ArticleListAdapter

    override fun initCustomData() {
        super.initCustomData()

        initClickListener()

        initBannerView()

        initRecyclerView()

        initRefreshView()

        val bannerDataDB = viewModel?.getBannerDataForDB()
        if (bannerDataDB.isNullOrEmpty()) { //本地数据为空，则从网络取
            getBannerDataForHttp()
        } else {
            updateBannerViewData(bannerDataDB)
        }

        val articleListDataDB = viewModel?.getArticleListDataForDB()
        if (articleListDataDB.isNullOrEmpty()) {
            getArticleListDataForHttp()
        } else {
            updateArticleListViewData(articleListDataDB)
        }

    }

    private fun initClickListener() {
        viewBinding?.ivSetting?.setOnClickListener {
            startActivity(Intent(this@MainActivity, SettingsActivity::class.java))
        }
    }

    private fun getArticleListDataForHttp() {
        viewModel?.getArticleListData()?.observeState(this) {
            onSuccess {
                updateArticleListViewData(it.datas)
            }
            onException {
                ToastUtils.show("数据请求发生异常,${it.message}")
            }
            onComplete {
                if (viewBinding?.refresh?.isRefreshing == true) { //数据请求完成，关闭刷新显示
                    viewBinding?.refresh?.isRefreshing = false
                }
            }
        }
    }

    private fun updateArticleListViewData(articleListDataList: List<ArticleListItemBean>) {
        articleListDatas.clear()
        articleListDatas.addAll(articleListDataList)
        articleListAdapter.notifyDataSetChanged()
    }

    private fun getBannerDataForHttp() {
        viewModel?.getBannerData()?.observeState(this) {
            onSuccess {
                LogUtil.e("数据请求成功===$it")
                updateBannerViewData(it)
            }
            onException {
                LogUtil.e(it, "数据请求发生异常")
                ToastUtils.show("数据请求发生异常,${it.message}")
            }
        }
    }

    private fun updateBannerViewData(bannerBeanList: List<BannerBean>) {
        bannerDatas.clear()
        bannerDatas.addAll(bannerBeanList)
        LogUtil.e("更新数据===bannerDatas===${bannerDatas.size}")

        viewBinding?.banner?.setDatas(bannerDatas)
    }

    private fun initRefreshView() {
        viewBinding?.refresh?.setColorSchemeColors(
            Color.parseColor("#a76283"),
            Color.parseColor("#ee7959"),
            Color.parseColor("#d23918"),
            Color.parseColor("#226b68")
        )
        viewBinding?.refresh?.setOnRefreshListener { //从网络请求数据
            getBannerDataForHttp()
            getArticleListDataForHttp()
        }
    }

    private fun initRecyclerView() {
        viewBinding?.recyclerView?.layoutManager = LinearLayoutManager(this)
        viewBinding?.recyclerView?.addItemDecoration(
            DividerItemDecoration(
                this, DividerItemDecoration.VERTICAL
            )
        )
        articleListAdapter = ArticleListAdapter(articleListDatas)
        viewBinding?.recyclerView?.adapter = articleListAdapter
        articleListAdapter.onItemClick = { v, pos, url, title ->
            val intent = Intent(this@MainActivity, WebViewActivity::class.java)
            intent.putExtra("url", url)
            intent.putExtra("title", title)
            startActivity(intent)
        }
    }

    private fun initBannerView() {
        viewBinding?.banner?.addBannerLifecycleObserver(this@MainActivity)
            ?.setAdapter(MyBannerAdapter(bannerDatas))
            ?.setIndicator(CircleIndicator(this@MainActivity))
            ?.setOnBannerListener(OnBannerListener<BannerBean> { data, position ->
                val intent = Intent(this@MainActivity, WebViewActivity::class.java)
                intent.putExtra("url", data.url)
                intent.putExtra("title", data.title)
                startActivity(intent)
            })
    }
}